package com.android.lovely.ui.fragment

import android.icu.text.DecimalFormat
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.R
import com.android.lovely.const.CreatedRoleRefresh
import com.android.lovely.data.RoleHistory
import com.android.lovely.databinding.AdapterLoadingFooterBinding
import com.android.lovely.databinding.FragmentWorkCreateRoleBinding
import com.android.lovely.databinding.ItemWorkRoleBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseFragment
import com.android.lovely.manager.LogManager
import com.android.lovely.room.role.CreateRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.android.lovely.ui.activity.CreateRoleActivity
import com.android.lovely.ui.activity.CreateRolePreviewActivity
import com.android.lovely.ui.activity.DetailActivity
import com.android.lovely.ui.adapter.DetailLoadAdapter
import com.android.lovely.ui.adapter.HomeTagsAdapter
import com.android.lovely.ui.viewmodel.WorkCreateViewModel
import com.android.lovely.user.UserManager
import com.kotlin.extensions.appContext
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/8 16:03
 */
class WorkRoleFragment : BaseFragment<FragmentWorkCreateRoleBinding>() {
    val viewModel by activityViewModels<WorkCreateViewModel>()

    val localAdapter by lazy {
        WorkLocalRoleAdapter()
    }
    val publicAdapter by lazy {
        WorkPublicRoleAdapter()
    }

    val contentAdapter by lazy {
        ConcatAdapter(ConcatAdapter.Config.Builder().setIsolateViewTypes(false).build())
    }

    private val loadAdapter by lazy {
        DetailLoadAdapter(
            AdapterLoadingFooterBinding.inflate(
                layoutInflater, mBinding.rv, false
            )
        )
    }


    override fun initView() {
        mBinding.llCarousel.isVisible = false
        mBinding.rv.adapter = contentAdapter
        mBinding.rv.layoutManager =GridLayoutManager(requireContext(), 2).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    val viewType = mBinding.rv.adapter?.getItemViewType(position)
                    return if (viewType == 1 || viewType == 888 || viewType == 101) 2 else 1
                }
            }
        }
        mBinding.rv.addItemDecoration(HomeListItemDecoration(10.dp));

        mBinding.flexState.setNoContentIcon(R.drawable.icon_no_search)
        mBinding.flexState.setNoContentText(getString(R.string.no_role_content))
        mBinding.flexState.setNoContentButton(getString(R.string.create_role), true) {
            requireActivity().startPage<CreateRoleActivity>()
        }

        mBinding.flexState.update()

        contentAdapter.addAdapter(publicAdapter)
        lifecycleScope.launchSafety {
            viewModel.roleType.observe(this@WorkRoleFragment) {
                if(it.first == 2){
                    contentAdapter.addAdapter(localAdapter)
                    contentAdapter.removeAdapter(publicAdapter)
                    contentAdapter.removeAdapter(loadAdapter)
                } else {
                    contentAdapter.addAdapter(publicAdapter)
                    contentAdapter.removeAdapter(localAdapter)
                }
                loadAdapter.loadMoreEnd = false
                loadAdapter.isLoading = false
                mBinding.flexState.displayProgress()
                viewModel.requestRole()
                mBinding.srlRefresh.isRefreshing = false
            }
        }
        viewModel.updateList.observe(requireActivity()) {
            if(it.first == 1) {
                if(it.second.isEmpty()) {
                    mBinding.flexState.displayNoContent()
                } else {
                    mBinding.flexState.displayMainContent()
                    publicAdapter.updateList(it.second)
                    if (!contentAdapter.adapters.contains(loadAdapter)) {
                        contentAdapter.addAdapter(loadAdapter)
                    }
                    mBinding.rv.smoothScrollToPosition(0)
                }
            } else {
                publicAdapter.insertList(it.second)
            }
            if(it.second.isNotEmpty()) {
                loadAdapter.isLoading = false
            } else {
                loadAdapter.isLoading = false
                loadAdapter.loadMoreEnd = true
            }
            mBinding.srlRefresh.isRefreshing = false
        }

        viewModel.updateLocalList.observe(requireActivity()) {
            if(viewModel.currentPages == 1) {
                localAdapter.updateList(it)
            } else {
                localAdapter.insertList(it)
            }
            if(localAdapter.getItems().isEmpty()) {
                mBinding.flexState.displayNoContent()
            } else {
                mBinding.flexState.displayMainContent()
            }
            mBinding.srlRefresh.isRefreshing = false
        }
        mBinding.srlRefresh.setOnRefreshListener {
            contentAdapter.removeAdapter(loadAdapter)
            loadAdapter.loadMoreEnd = false
            loadAdapter.isLoading = false
            viewModel.requestRole()
        }
        loadAdapter.onLoadMoreListener = {
            viewModel.loadMore {
                publicAdapter.endLoading()
            }
        }
        publicAdapter.onLoadMore = {
            viewModel.loadMore {
                publicAdapter.endLoading()
            }
        }
        mBinding.flexState.displayProgress()
        viewModel.requestRole()
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<CreatedRoleRefresh>().collect {
                loadAdapter.loadMoreEnd = false
                loadAdapter.isLoading = false

                mBinding.flexState.displayProgress()
                viewModel.requestRole()
                mBinding.srlRefresh.isRefreshing = false
            }
        }
    }


    override suspend fun initData() {

    }

    class WorkLocalRoleAdapter : BaseAdapter<CreateRole, ItemWorkRoleBinding>() {
        override fun bindViewWithHolderDetails(
            holder: ViewHolder,
            item: CreateRole?,
            binding: ItemWorkRoleBinding,
            position: Int
        ) {
            item ?: return
            binding.apply {
                ivImage.loadWithPlaceholder(item.cards.firstOrNull()?.localePath) {
                    crossfade(true)
                }
                tvAuth.isGone = UserManager.userInfo?.name.isNullOrEmpty()
                tvAuth.text = "@${UserManager.userInfo?.name}"

                tvName.text = item.nickName
                imgCount.text = item.cards.size.toString()
                collectCount.text = "0"
                ivNsfw.isVisible = item.nsfw
                tvContent.text = item.introduction
                rvTag.isVisible = item.keywords.isNotEmpty()
                if(item.keywords.isNotEmpty()) {
                    val adapter = HomeTagsAdapter()
                    rvTag.layoutManager =  LinearLayoutManager(rvTag.context, RecyclerView.HORIZONTAL, false)
                    rvTag.adapter =adapter
                    adapter.updateList(item.keywords)
                }
                rvTag.setOnTouchListener { _, _ ->
                    true
                }
                root.clickable {
                    if (item.createId > 0) {
                        appContext.startPage<CreateRolePreviewActivity>("role_id" to item.id)
                    } else {
                        appContext.startPage<CreateRoleActivity>("role_id" to item.id)
                    }
                }
            }
        }

    }
    class WorkPublicRoleAdapter : RecyclerView.Adapter<WorkPublicRoleAdapter.BaseViewHolder>() {
        protected val list = arrayListOf<RoleHistory>()


        fun getData(): List<RoleHistory> = list

        override fun getItemViewType(position: Int): Int {
            return 100
        }

        override fun getItemCount(): Int {
            return list.size
        }


        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
            return DefaulterViewHolder(parent)
        }

        protected fun getItemAt(position: Int): RoleHistory? {
            if (position > list.size) {
                return null
            }
            return list[position]
        }

        var onLoadMore: (() -> Unit)? = null

        private var isLoading = false

        fun endLoading() {
            isLoading = false
        }

        open fun updateList(newList: List<RoleHistory>) {
            list.clear()
            list.addAll(newList)
            notifyDataSetChanged()
        }

        fun insertList(newItems: List<RoleHistory>, position: Int = list.size) {
            list.addAll(position, newItems)
            notifyItemRangeInserted(position, newItems.size)
        }

        override fun onBindViewHolder(p0: BaseViewHolder, p1: Int) {
            val item = getItemAt(p1) ?: return
            p0.binding.apply {
                ivImage.loadWithPlaceholder(item.coverImage["url"]) {
                    crossfade(true)
                }
                tvAuth.isGone = UserManager.userInfo?.name.isNullOrEmpty()
                tvAuth.text = "@${UserManager.userInfo?.name}"

                tvName.text = item.name
                imgCount.text = item.cardNum.toString()
                collectCount.text = if (item.collectNum < 1000) {
                    item.collectNum.toString()
                } else if (item.collectNum < 1000 * 1000) {
                    "${DecimalFormat("0.##").format((item.collectNum.toFloat() / 1000))}K"
                } else {
                    "${DecimalFormat("0.##").format((item.collectNum.toFloat() / 1000_000))}M"
                }
                ivNsfw.isVisible = item.type == 1
                tvContent.text = item.personality
                ivStatus.setImageResource(if (item.status == 1) R.drawable.icon_role_load else if (item.status == 2) R.drawable.icon_role_success else R.drawable.icon_role_warn)
                rvTag.isVisible = item.searchTag.isNotEmpty()
                if(item.searchTag.isNotEmpty()) {
                    val adapter = HomeTagsAdapter()
                    rvTag.layoutManager =  LinearLayoutManager(rvTag.context, RecyclerView.HORIZONTAL, false)
                    rvTag.adapter =adapter
                    adapter.updateList(item.searchTag.split(","))
                }
                rvTag.setOnTouchListener { _, _ ->
                    true
                }
                ivEdit.clickable {
                    val option = item.toCreateRole()
                    applicationScope.launchSafety {
                        CreateRoleDataBase.dao.save(option)
                        appContext.startPage<CreateRolePreviewActivity>("role_id" to option.id)
                    }
                }
                root.clickable {
                    LogManager.reportEvent(item.id, "click")
                    DetailActivity.launch(item.botId)
                }
            }
        }

        class DefaulterViewHolder(
            parent: ViewGroup, binding: ItemWorkRoleBinding = ItemWorkRoleBinding.inflate(
                parent.layoutInflater, parent, false
            )
        ) : BaseViewHolder(binding)


        open class BaseViewHolder(val binding: ItemWorkRoleBinding) : RecyclerView.ViewHolder(binding.root)

    }

}